<template>
  <b-navbar id="chat-navbar" toggleable="md" type="dark" variant="info">
    <b-navbar-brand href="#">
      Vue Chat
    </b-navbar-brand>
    <b-navbar-nav class="ml-auto">
      <b-nav-text>{{ user.name }} | </b-nav-text>
      <b-nav-item href="#" active @click="onLogout">Logout</b-nav-item>
    </b-navbar-nav>
  </b-navbar>
</template>

<script>
import { mapState, mapActions, mapMutations } from "vuex";
export default {
  name: "ChatNavBar",
  components: {},
  data() {
    return {};
  },
  computed: {
    ...mapState(["user", "reconnect"])
  },
  watch: {},
  methods: {
    ...mapActions(["logout", "login"]),
    ...mapMutations(["setReconnect"]),
    onLogout() {
      this.$router.push({ path: "/" });
      this.logout();
    },
    // 页面刷新发生时，将调用此方法。它首先检查状态user.username已设置。如果已注册，则意味着用户尚未注销。状态reconnect设置为true。
    unload() {
      if (this.user.username) {
        // User hasn't logged out
        this.setReconnect(true);
      }
    }
  },
  created() {},
  mounted() {
    // 检查是否state.reconnect已设置为true。如果是这样，则执行登录过程，从而将我们的聊天应用程序重新连接回我们的ChatKit服务
    window.addEventListener("beforeunload", this.unload);
    if (this.reconnect) {
      this.login(this.user.username);
    }
  }
};
</script>
<style>
#chat-navbar {
  margin-bottom: 15px;
}
</style>
